﻿package
{
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent
	import flash.ui.Keyboard
	import com.chandings.view.components.SpaceShip
	
	/**
	 * ...
	 */
	public class SpaceExplorer extends Sprite
	{
		protected var spaceShip:SpaceShip;
		
		//variables for keyboard events
		protected var leftKeyDown:Boolean;
		protected var rightKeyDown:Boolean;
		protected var upKeyDown:Boolean;
		protected var downKeyDown:Boolean;
		
		public function SpaceExplorer():void
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			spaceShip = new SpaceShip();
			spaceShip.setStage(stage);
			addKeyboadEvent();
			addEventListener(Event.ENTER_FRAME, gameLoop);
		}
		
		private function gameLoop(e:Event):void 
		{
			if (leftKeyDown)
			{
				spaceShip.rotation -= spaceShip.rotationalAccelaration;
			}
			else if (rightKeyDown)
			{
				spaceShip.rotation += spaceShip.rotationalAccelaration;
			}
			if (spaceShip.rotation > .03  || spaceShip.rotation < -.03)
			{
				spaceShip.rotation *= spaceShip.rotationalFriction;
			}else 
			{
				spaceShip.rotation = 0;
			}
			if (upKeyDown)
			{
				spaceShip.velocity += spaceShip.accelaration;
			}
			else if (downKeyDown)
			{
				spaceShip.velocity -= spaceShip.accelaration;
			}
			if (spaceShip.velocity > .03  || spaceShip.velocity < -.03)
			{
				spaceShip.velocity *= spaceShip.friction;
			}else 
			{
				spaceShip.velocity = 0;
			}
		}
		
		private function addKeyboadEvent():void
		{
			stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
		}
		
		private function keyReleased(e:KeyboardEvent):void 
		{
			switch(e.keyCode)
			{
				case Keyboard.LEFT:
					leftKeyDown = false;
				break;
				case Keyboard.RIGHT:
					rightKeyDown = false;
				break;
				case Keyboard.UP:
					upKeyDown = false;
				break;
				case Keyboard.DOWN:
					downKeyDown = false;
				break;
			}
		}
		
		private function keyPressed(e:KeyboardEvent):void 
		{
			trace(e.keyCode)
			trace(Keyboard.LEFT)
			switch(e.keyCode)
			{
				case Keyboard.LEFT:
					leftKeyDown = true;
				break;
				case Keyboard.RIGHT:
					rightKeyDown = true;
				break;
				case Keyboard.UP:
					upKeyDown = true;
				break;
				case Keyboard.DOWN:
					downKeyDown = true;
				break;
			}
		}
		
	}
	
}